#include "utils/load_data.hpp"
//日志相关变量
static bool enable_gait_log = false;  // 控制是否记录日志
static std::ofstream gait_log_file;    // 文件流对象

M_date m_data;
int isStd = 0;


//读取csv////
std::vector<sensorData> load_csv_data(const std::string& filepath) 
{
    std::vector<sensorData> data;
    std::ifstream file(filepath);
    if (!file.is_open()) 
    {
        throw std::runtime_error("Unable to open CSV file: " + filepath);
    }

    std::string line;
    // 跳过标题行
    std::getline(file, line);

    while (std::getline(file, line)) 
    {
        std::stringstream ss(line);
        std::string field;
        std::vector<std::string> fields;

        while (std::getline(ss, field, ',')) 
        {
            fields.push_back(field);
        }

        // if (fields.size() < 12) {
        if (fields.size() < 11) 
        {
            continue; // 跳过格式错误的行
        }

        sensorData sd;
        try {
            // 解析所需列
            sd.imu_gyr = std::stof(fields[3]);      // leftImuData
            sd.imu_euler = std::stof(fields[9]);    // euler_p
            // sd.tof_distance = std::stof(fields[11]);
            sd.tof_distance = std::stof(fields[5]); // handle_tof
        } 
        catch (const std::exception& e) {
            std::cerr << "Error parsing line: " << line << " - " << e.what() << std::endl;
            continue;
        }

        data.push_back(sd);
    }
    return data;
}
////////////

//存储日至
static void logData(int64_t cnt,sensorData& data,gaitParam& gait_param)
{
    if(enable_gait_log && gait_log_file.is_open())
    {
        gait_log_file
            <<cnt<<","
            <<data.imu_euler<<","
            <<data.imu_gyr<<","
            <<data.tof_distance<<","
            <<gait_param.event_t.hs_t<<","
            <<gait_param.event_t.to_t<<"," 
            <<gait_param.event_t.T_fid<<","
            <<gait_param.event_t.T_begin<<","
            <<gait_param.event_t.T_end<<","
            <<m_data.m_hpr<<","
            <<m_data.m_std<<","
            <<m_data.m_swd<<","
            <<isStd
            <<std::endl;
    }
}

 void log_error_to_file(const std::string& message) {
    std::ofstream logFile("log.txt", std::ios_base::app);
    if (logFile.is_open()) {
        // 获取当前时间
        auto now = std::chrono::system_clock::now();
        auto now_time = std::chrono::system_clock::to_time_t(now);
        
        logFile << "[" << std::put_time(std::localtime(&now_time), "%Y-%m-%d %H:%M:%S") << "] "
                << "ERROR: " << message << std::endl;
        logFile.close();
    }
}